import { defineStore } from 'pinia'
import userApi from '../apis/Userapi'

// 定义凭证接口
interface Credentials {
  username: string
  password: string
}

// 定义用户接口
interface User {
  id: string
  username: string
  email?: string
  role?: string
  [key: string]: any
}

// 定义响应接口
interface LoginResponse {
  token: string
  user: User
}

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null as User | null,
    token: localStorage.getItem('token') || null,
  }),
  actions: {
    async login(credentials: Credentials) {
      const response = await userApi.login(credentials)
      const res = response.data as LoginResponse
      this.token = res.token
      this.user = res.user
      localStorage.setItem('token', res.token)
    },
    async logout() {
      this.token = null
      this.user = null
      localStorage.removeItem('token')
    },
    async fetchCurrentUser() {
      if (this.token) {
        const response = await userApi.getCurrentUser()
        this.user = response.data as User
      }
    },
  },
  getters: {
    isAuthenticated: (state) => !!state.token,
  },
})
